package com.daryl.db;

import com.daryl.test.Person;
import com.google.gson.Gson;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class MiniMongodb {
    private static final String _uuid = "_uuid";

    /**
     * 创建数据库
     * @param path
     * @throws Exception
     */
    public void createDataBse(String path) throws Exception {
        FileOutputStream file = new FileOutputStream(path);
        Document document = new Document();
        Element root = new Element("database");

        Element table1 = new Element("table");
        Element table2 = new Element("table");


        table1.setAttribute("name","system.indexs");
        table2.setAttribute("name","system.users");


        root.setContent(table1);
        root.setContent(table2);

        document.setRootElement(root);
        XMLOutputter out  = new XMLOutputter();
        out.output(document,file);

        System.out.println("===================create database success=================================");

    }

    /**
     * 创建表
     * @param path
     * @param tableName
     * @throws IOException
     * @throws JDOMException
     */
    public void createTable(String path , String tableName) throws IOException, JDOMException {

        FileInputStream file = new FileInputStream(path);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(file);
        Element root = document.getRootElement();
        Element table = new Element("table");
        table.setAttribute("name",tableName);
        root.setContent(table);
        XMLOutputter out = new XMLOutputter();
        out.output(document,new FileOutputStream(path));
        System.out.println("===================create table success=================================");
    }

    /**
     * 插入数据
     * @param path
     * @param tableName
     * @param po
     * @return
     * @throws IOException
     * @throws JDOMException
     */
    public boolean insertData(String path, String tableName, Object po) throws IOException, JDOMException {

        Gson gson = new Gson();
        boolean flag = false;
        FileInputStream file = new FileInputStream(path);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(file);
        Element root = document.getRootElement();

        List<Element> tableList = root.getChildren();
        for(Element table : tableList){
            if(table.getAttributeValue("name").equals(tableName)){
                Map base = new HashMap();
                base.put(_uuid, UUID.randomUUID().toString());
                Element data =  new Element("data");
                String json = gson.toJson(po);
                Map map = gson.fromJson(json,Map.class);
                base.putAll(map);
                data.addContent(gson.toJson(base));
                table.addContent(data);
            }

        }

        XMLOutputter out = new XMLOutputter();
        out.output(document,new FileOutputStream(path));
        flag = true;
        System.out.println("==============insert data success==============================");
        return flag;
    }

    /**
     * 更新数据
     * @param path
     * @param tableName
     * @param po
     * @throws IOException
     * @throws JDOMException
     */
    public void updateData(String path, String tableName, Object po) throws IOException, JDOMException {
        Gson gson = new Gson();
        FileInputStream file = new FileInputStream(path);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(file);
        Element root = document.getRootElement();

        List<Element> tableList = root.getChildren();
        for(Element table : tableList){
            if(table.getAttributeValue("name").equals(tableName)){
                List<Element> rowList = table.getChildren();
                for(Element row : rowList){
                    Map map = gson.fromJson(row.getText(),Map.class);
                    Map newMap = gson.fromJson(gson.toJson(po),Map.class);
                    if(map.get(_uuid).equals(newMap.get(_uuid))){
                        map.putAll(newMap);
                        Element data = new Element("data");
                        data.setText(gson.toJson(map));
                        table.removeContent(row);
                        table.addContent(data);
                        break;
                    }
                }
            }
        }
        XMLOutputter out = new XMLOutputter();
        out.output(document,new FileOutputStream(path));
        System.out.println("==============update data success==============================");

    }

    public void deleteData(String path, String tableName, Object po) throws IOException, JDOMException {
        Gson gson = new Gson();
        FileInputStream file = new FileInputStream(path);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(file);
        Element root = document.getRootElement();

        List<Element> tableList = root.getChildren();
        for(Element table : tableList){
            if(table.getAttributeValue("name").equals(tableName)){
                List<Element> rowList = table.getChildren();
                for(Element row : rowList){
                    Map map = gson.fromJson(row.getText(),Map.class);
                    Map newMap = gson.fromJson(gson.toJson(po),Map.class);
                    if(map.get(_uuid).equals(newMap.get(_uuid))){
                        table.removeContent(row);
                        break;
                    }
                }
            }
        }
        XMLOutputter out = new XMLOutputter();
        out.output(document, new FileOutputStream(path));
        System.out.println("==============delete data success==============================");
    }

    /**
     * 获取表的全部数据
     * @param path
     * @param tableName
     * @return
     */
    public List<Map> selectTableData(String path, String tableName) throws IOException, JDOMException {
        Gson gson = new Gson();
        FileInputStream file = new FileInputStream(path);
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(file);
        Element root = document.getRootElement();

        List<Map> list = new ArrayList<Map>();
        List<Element> tableList = root.getChildren();
        for(Element table : tableList){
            if(table.getAttributeValue("name").equals(tableName)){
                List<Element> rowList = table.getChildren();
                for(Element row : rowList){
                    String data = row.getText();
                    if(data == null){
                        break;
                    }
                    Map map = gson.fromJson(data,Map.class);
                    list.add(map);
                }
            }
        }
        return list;
    }
}
